package main

import (
	"fmt"
	"sync"
)

/*
	goroutine + channel
	开启两个协程，一个写入1-100数据，一个读取数据，进行计算
*/
func write2(ch chan int) {
	defer wg1.Done()
	for i := 0; i < 100; i++ {
		ch <- i + 1
	}
	close(ch)
}

var (
	once1 sync.Once
	wg1 sync.WaitGroup
)

func cal2(ch1, ch2 chan int) {
	defer wg1.Done()
	for {
		if val, ok := <-ch1; ok {
			ch2 <- val * val
		} else {
			break
		}
	}
	once1.Do(func() { close(ch2) }) // 确定close（）这会执行一次
}
func main() {
	ch1 := make(chan int, 50)
	ch2 := make(chan int, 100)

	wg1.Add(6)
	go write2(ch1)
	go cal2(ch1, ch2)
	go cal2(ch1, ch2)
	go cal2(ch1, ch2)
	go cal2(ch1, ch2)
	go cal2(ch1, ch2)

	wg1.Wait()
	for val := range ch2 {
		fmt.Println(val)
	}
	fmt.Println("main end")
}
